﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Curling.CurlingServer;

namespace Curling
{
    public partial class VSPage : PhoneApplicationPage
    {
        readonly IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

        CurlingServiceClient CurlingService;
        PlayerProfile Opponent;

        bool GoBack = false;
        bool Loading = false;
        bool GoPlay = false;

        DispatcherTimer Timer;
        DispatcherTimer CheckRequestResultTimer;

        enum PageState
        { 
            Normal,
            WaitingOpponent,
            OpponentConnected
        }

        private PageState state_;
        private PageState state
        {
            get
            {
                return state_;
            }
            set
            {
                if (state_ != value)
                {
                    state_ = value;

                    if (state_ == PageState.Normal)
                    {
                        VisualStateManager.GoToState(this, "Normal", false);
                        //WaitGroup.Opacity = 0.0;
                        //PlayButton.Content = "PLAY";
                        WaitingBar.IsIndeterminate = false;
                        //DisableContent.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    else if (state_ == PageState.WaitingOpponent)
                    {
                        //WaitGroup.Opacity = 1.0;
                        //PlayButton.Content = "CANCEL";
                        WaitingBar.IsIndeterminate = true;
                        //DisableContent.Visibility = System.Windows.Visibility.Visible;
                        VisualStateManager.GoToState(this, "WaitingOpponent", false);
                    }
                    else if (state_ == PageState.OpponentConnected)
                    {
                        WaitingBar.IsIndeterminate = false;
                        VisualStateManager.GoToState(this, "OpponentConnected", false);
                    }
                }
            }
        }

        PlayerType player1Type = PlayerType.Person;
        PlayerType Player1Type
        {
            get { return player1Type; }
            set
            {
                player1Type = value;

                switch (player1Type)
                {
                    case PlayerType.Person:
                    {
                        FirstPlayerText.IsEnabled = true;
                        FirstPlayerText.Text = "Player 1";
                        FirstPlayerTypeImage.Source = new BitmapImage(new Uri("Images/Players/Player.png", UriKind.Relative));
                        break;
                    }
                    case PlayerType.Computer:
                    {
                        FirstPlayerText.IsEnabled = false;
                        FirstPlayerText.Text = "Computer";
                        FirstPlayerTypeImage.Source = new BitmapImage(new Uri("Images/Players/Computer2.png", UriKind.Relative));
                        break;
                    }                    
                }
            }
        }

        PlayerType player2Type = PlayerType.Person;
        PlayerType Player2Type
        {
            get { return player2Type; }
            set
            {
                player2Type = value;

                switch (player2Type)
                {
                    case PlayerType.Person:
                    {
                        SecondPlayerText.IsEnabled = true;
                        SecondPlayerText.Text = "Player 2";
                        SecondPlayerTypeImage.Source = new BitmapImage(new Uri("Images/Players/Player.png", UriKind.Relative));
                        break;
                    }
                    case PlayerType.Computer:
                    {
                        SecondPlayerText.IsEnabled = false;
                        SecondPlayerText.Text = "Computer";
                        SecondPlayerTypeImage.Source = new BitmapImage(new Uri("Images/Players/Computer2.png", UriKind.Relative));
                        break;
                    }
                    case PlayerType.Internet:
                    {
                        SecondPlayerText.IsEnabled = false;
                        SecondPlayerText.Text = "Internet";
                        SecondPlayerTypeImage.Source = new BitmapImage(new Uri("Images/Players/Internet.png", UriKind.Relative));
                        break;
                    }
                }
            }
        }

        public VSPage()
        {
            InitializeComponent();
            
            FadeOut.Completed += new EventHandler(FadeOut_Completed);

            CheckRequestResultTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1.0) };
            CheckRequestResultTimer.Tick += new EventHandler(CheckRequestResultTimer_Tick);
        }

        void CheckRequestResultTimer_Tick(object sender, EventArgs e)
        {
            if (state == PageState.WaitingOpponent)
            {
                CurlingService.CheckRequestResultAsync(App.AuthToken, ((PlayerProfile)PhoneApplicationService.Current.State["Opponent"]).ID);
            }

            CheckRequestResultTimer.Stop();
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!Loading)
            {
                if (state == PageState.WaitingOpponent)
                {
                    state = PageState.Normal;
                    SecondPlayerText.Text = "Internet";
                    e.Cancel = true;

                    return;
                }

                if (!GoBack)
                {
                    FadeOut.Begin();
                    GoBack = true;
                }

                e.Cancel = true;
            }
        }

        void FadeOut_Completed(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            PhoneApplicationService.Current.State.Remove("GoToMenu");

            if (PhoneApplicationService.Current.State.ContainsKey("ToMenu"))
            {
                ContentGrid.Visibility = System.Windows.Visibility.Collapsed;
                LoadingGrid.Visibility = System.Windows.Visibility.Collapsed;
                
                PhoneApplicationService.Current.State.Remove("NeedSaveGameManager");
                PhoneApplicationService.Current.State.Remove("GameManager");

                NavigationService.GoBack();
            }
            else
            {   
                if (settings.Contains("Player1Type"))
                {
                    Player1Type = (PlayerType)settings["Player1Type"];
                }

                if (settings.Contains("Player2Type"))
                {
                    Player2Type = (PlayerType)settings["Player2Type"];
                }

                if (settings.Contains("Player1") && Player1Type == PlayerType.Person)
                {
                    FirstPlayerText.Text = (string)settings["Player1"];
                }

                if (settings.Contains("Player2") && Player2Type == PlayerType.Person)
                {
                    SecondPlayerText.Text = (string)settings["Player2"];
                }

                if (Player1Type == PlayerType.Computer && Player2Type == PlayerType.Internet)
                {
                    PlayButton.IsEnabled = false;
                }

                if (!PhoneApplicationService.Current.State.ContainsKey("FromMultiPlayer"))
                {
                    FadeIn.Begin();

                    state = PageState.Normal;
                }
                else
                {
                    if (PhoneApplicationService.Current.State.ContainsKey("Opponent"))
                    {
                        Opponent = (PlayerProfile)PhoneApplicationService.Current.State["Opponent"];
                        SecondPlayerText.Text = Opponent.Name;

                        CurlingService = (CurlingServiceClient)PhoneApplicationService.Current.State["CurlingService"];
                        CurlingService.CheckRequestResultCompleted += new EventHandler<CheckRequestResultCompletedEventArgs>(CurlingService_CheckRequestResultCompleted);

                        if (!PhoneApplicationService.Current.State.ContainsKey("Accepted"))
                        {
                            state = PageState.WaitingOpponent;

                            CheckRequestResultTimer.Start();
                        }
                        else
                        {
                            PhoneApplicationService.Current.State.Remove("Accepted");

                            state = PageState.OpponentConnected;

                            Play();
                        }
                    }

                    PhoneApplicationService.Current.State.Remove("FromMultiPlayer");
                    FadeInBack.Begin();
                }
            }

            GoPlay = false;
        }

        private void PlayButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            /*if (state == PageState.OpponentConnected)
            { 
            
            }
            else*/ if (state == PageState.WaitingOpponent)
            {
                state = PageState.Normal;
                
                SecondPlayerText.Text = "Internet";

                return;
            }
            else
            {
                if (!GoPlay)
                {
                    Play();
                }
            }
        }

        void Play()
        {
            if (CurlingService != null)
            {
                CurlingService.CheckRequestResultCompleted -= new EventHandler<CheckRequestResultCompletedEventArgs>(CurlingService_CheckRequestResultCompleted);
            }

            PhoneApplicationService.Current.State["resume"] = false;
            PhoneApplicationService.Current.State["Player1Name"] = FirstPlayerText.Text;
            PhoneApplicationService.Current.State["Player2Name"] = SecondPlayerText.Text;
            PhoneApplicationService.Current.State["Player1Type"] = Player1Type;
            PhoneApplicationService.Current.State["Player2Type"] = Player2Type;

            GoPlay = true;

            if (Player2Type == PlayerType.Internet)
            {
                if (state == PageState.Normal)
                {
                    Timer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(0.2) };
                    Timer.Tick += new EventHandler(Timer_Tick);
                    Timer.Start();

                    BeginPlay.Begin();
                }
                else
                {
                    CurlingService.IsIamFirstPlayerCompleted += new EventHandler<IsIamFirstPlayerCompletedEventArgs>(CurlingService_IsIamFirstPlayerCompleted);
                    CurlingService.IsIamFirstPlayerAsync(App.AuthToken);
                }
            }
            else
            {
                BeginPlay.Begin();

                Loading = true;
                LoadingAnimation.Begin();

                if (Player1Type == PlayerType.Computer && Player2Type == PlayerType.Computer)
                {
                    ComputerVSComputer();
                }
                else if (Player1Type == PlayerType.Computer || Player2Type == PlayerType.Computer)
                {
                    PlayerVSComputer();
                }
                else
                {
                    PlayerVSPlayer();
                }

                NavigationService.Navigate(new Uri("/GamePage.xaml", UriKind.Relative));
            }
        }

        void CurlingService_IsIamFirstPlayerCompleted(object sender, IsIamFirstPlayerCompletedEventArgs e)
        {
            if (e.Error == null && e.Result.HasValue)
            {
                BeginPlay.Begin();

                Loading = true;
                LoadingAnimation.Begin();

                //PhoneApplicationService.Current.State["IamFirst"] = e.Result;

                if (e.Result.Value == false)
                {
                    PhoneApplicationService.Current.State["Player1Name"] = SecondPlayerText.Text;
                    PhoneApplicationService.Current.State["Player2Name"] = FirstPlayerText.Text;
                    PhoneApplicationService.Current.State["Player1Type"] = Player2Type;
                    PhoneApplicationService.Current.State["Player2Type"] = Player1Type;
                }

                NavigationService.Navigate(new Uri("/GamePage.xaml", UriKind.Relative));

                PlayerVSInternet();

                CurlingService.IsIamFirstPlayerCompleted -= new EventHandler<IsIamFirstPlayerCompletedEventArgs>(CurlingService_IsIamFirstPlayerCompleted);
            }
            else
            {
                MessageBox.Show("Connection with a server is lost. Try later.", "Network error", MessageBoxButton.OK);

                SecondPlayerText.Text = "Internet";

                GoPlay = false;
            }
        }

        void CurlingService_CheckRequestResultCompleted(object sender, CheckRequestResultCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.HasValue)
                {
                    if (e.Result.Value == true)
                    {
                        Play();
                        //MessageBox.Show("Accepted");
                    }
                    else
                    {
                        MessageBox.Show("Player '" + Opponent.Name + "' rejected your request. Try with someone else.", "Failure", MessageBoxButton.OK);

                        SecondPlayerText.Text = "Internet";
                    }

                    state = PageState.Normal;
                    //WaitForResponse = false;
                }
                else
                {
                    CheckRequestResultTimer.Start();
                }
            }
            else
            {
                MessageBox.Show("Connection with a server is lost. Try later.", "Network error", MessageBoxButton.OK);
            }
        }

        void Timer_Tick(object sender, EventArgs e)
        {
            Timer.Stop();

            NavigationService.Navigate(new Uri("/MultiPlayerPage.xaml", UriKind.Relative));
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            if (PhoneApplicationService.Current.State.ContainsKey("ToMenu"))
            {
                PhoneApplicationService.Current.State.Remove("ToMenu");
            }
            else
            {
                settings["Player1"] = FirstPlayerText.Text;
                settings["Player2"] = SecondPlayerText.Text;
                settings["Player1Type"] = Player1Type;
                settings["Player2Type"] = Player2Type;
            }

            //PhoneApplicationService.Current.State.Remove("Opponent");
            //PhoneApplicationService.Current.State.Remove("CurlingService");
        }

        private void FirstPlayerText_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                this.Focus();
            }
        }

        private void SecondPlayerText_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                this.Focus();
            }
        }

        private void FirstPlayerTypeButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            PlayButton.IsEnabled = true;

            if (Player1Type == PlayerType.Person)
            {
                Player1Type = PlayerType.Computer;

                if (Player2Type == PlayerType.Internet)
                {
                    PlayButton.IsEnabled = false;
                }
            }
            else if (Player1Type == PlayerType.Computer)
            {
                Player1Type = PlayerType.Person;
            }
        }

        private void SecondPlayerTypeButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            PlayButton.IsEnabled = true;

            if (Player2Type == PlayerType.Person)
            {
                Player2Type = PlayerType.Computer;
            }
            else if (Player2Type == PlayerType.Computer)
            {
                Player2Type = PlayerType.Internet;

                if (Player1Type == PlayerType.Computer)
                {
                    PlayButton.IsEnabled = false;
                }
            }
            else if (Player2Type == PlayerType.Internet)
            {
                Player2Type = PlayerType.Person;
            }
        }

        private void PlayerVSPlayer()
        { }

        private void PlayerVSComputer()
        { }

        private void ComputerVSComputer()
        { }

        private void PlayerVSInternet()
        { }
    }
}
